# backend/routers/auth_router.py
import logging
from datetime import timedelta

from fastapi import APIRouter, Depends, HTTPException
from fastapi import Body
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from backend.crud.user_crud import create_user, get_user_by_username
from backend.dependencies import get_db
from backend.schemas import Token, UserCreate, User
from backend.utils.config import ACCESS_TOKEN_EXPIRE_MINUTES
from backend.utils.security import create_access_token, verify_password
from backend.utils.security import refresh_access_token
from backend.utils.security import get_password_hash

router = APIRouter()


@router.post("/register", response_model=User, summary="用户注册")
def register(user: UserCreate, db: Session = Depends(get_db)):
    """注册新用户"""
    db_user = get_user_by_username(db, username=user.username)
    if db_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    return create_user(db, user.username, user.password, user.full_name)


@router.post("/login", response_model=Token, summary="用户登录")
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    """用户登录端点"""
    return _login(form_data.username, form_data.password, db)


@router.post("/token", response_model=Token, include_in_schema=False)
def token_endpoint(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    """兼容 OAuth2 的 /token 端点"""
    return _login(form_data.username, form_data.password, db)


def _login(username: str, password: str, db: Session):
    """通用的登录逻辑"""
    user = get_user_by_username(db, username)
    logging.debug(f"User {username} is trying to log in")
    if not user:
        # 防止时序攻击 - 使用固定时间验证
        get_password_hash("dummy_password")
        raise HTTPException(
            status_code=401,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # 验证密码
    if not verify_password(password, user.hashed_password):
        raise HTTPException(
            status_code=401,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )

    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username},
        expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}


@router.post("/refresh", response_model=Token, summary="刷新访问令牌")
def refresh_token(
        refresh_token: str = Body(..., embed=True),
):
    """使用刷新令牌获取新的访问令牌"""
    try:
        new_access_token = refresh_access_token(refresh_token)
        return {"access_token": new_access_token, "token_type": "bearer"}
    except HTTPException as e:
        raise e
